/**
 * 认证服务
 * 处理用户登录、登出、权限验证等认证相关业务逻辑
 */

import { request } from '@/utils/request'
import { API_ENDPOINTS, STORAGE_KEYS } from '@/constants'
import type { LoginForm, UserInfo, LoginResponse } from '@/types/user'

export class AuthService {
  /**
   * 用户登录
   */
  static async login(loginForm: LoginForm): Promise<LoginResponse> {
    try {
      const response = await request.post(API_ENDPOINTS.LOGIN, loginForm)
      
      // 保存 token
      if (response.data.token) {
        localStorage.setItem(STORAGE_KEYS.TOKEN, response.data.token)
      }
      
      return response.data
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  /**
   * 用户登出
   */
  static async logout(): Promise<void> {
    try {
      await request.post(API_ENDPOINTS.LOGOUT)
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 清除本地存储
      localStorage.removeItem(STORAGE_KEYS.TOKEN)
      localStorage.removeItem(STORAGE_KEYS.USER_INFO)
    }
  }

  /**
   * 获取用户信息
   */
  static async getUserInfo(): Promise<UserInfo> {
    try {
      const response = await request.get(API_ENDPOINTS.USER_INFO)
      
      // 保存用户信息
      if (response.data) {
        localStorage.setItem(STORAGE_KEYS.USER_INFO, JSON.stringify(response.data))
      }
      
      return response.data
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  /**
   * 刷新 token
   */
  static async refreshToken(): Promise<string> {
    try {
      const response = await request.post(API_ENDPOINTS.REFRESH_TOKEN)
      
      if (response.data.token) {
        localStorage.setItem(STORAGE_KEYS.TOKEN, response.data.token)
        return response.data.token
      }
      
      throw new Error('刷新 token 失败')
    } catch (error) {
      console.error('刷新 token 失败:', error)
      throw error
    }
  }

  /**
   * 检查是否已登录
   */
  static isLoggedIn(): boolean {
    const token = localStorage.getItem(STORAGE_KEYS.TOKEN)
    return !!token
  }

  /**
   * 获取当前 token
   */
  static getToken(): string | null {
    return localStorage.getItem(STORAGE_KEYS.TOKEN)
  }

  /**
   * 获取缓存的用户信息
   */
  static getCachedUserInfo(): UserInfo | null {
    try {
      const userInfo = localStorage.getItem(STORAGE_KEYS.USER_INFO)
      return userInfo ? JSON.parse(userInfo) : null
    } catch (error) {
      console.error('解析用户信息失败:', error)
      return null
    }
  }

  /**
   * 检查权限
   */
  static hasPermission(permission: string): boolean {
    const userInfo = this.getCachedUserInfo()
    if (!userInfo || !userInfo.permissions) {
      return false
    }
    
    return userInfo.permissions.includes(permission)
  }

  /**
   * 检查多个权限（需要全部拥有）
   */
  static hasAllPermissions(permissions: string[]): boolean {
    const userInfo = this.getCachedUserInfo()
    if (!userInfo || !userInfo.permissions) {
      return false
    }
    
    return permissions.every(permission => userInfo.permissions.includes(permission))
  }

  /**
   * 检查多个权限（拥有任意一个即可）
   */
  static hasAnyPermission(permissions: string[]): boolean {
    const userInfo = this.getCachedUserInfo()
    if (!userInfo || !userInfo.permissions) {
      return false
    }
    
    return permissions.some(permission => userInfo.permissions.includes(permission))
  }
}
